import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import { encryptPassword } from 'src/utils/cryptogram';
import { omit } from 'lodash';

@Injectable()
export class AuthService {
    constructor(
        private readonly userService: UserService,
        private readonly jwtService: JwtService,
    ) {}

    // JWT验证 - step-2 校验用户信息
    async validateUser(username: string, password: string): Promise<any> {
        console.log('JWT验证 - Step 2: 校验用户信息');

        const user = await this.userService.findOne(username)
        if (user) {
            const salt = user.salt
            const hashedPassword = user.password
            const hashPassword = encryptPassword(password, salt)
            if (hashedPassword === hashPassword) {
                return {
                    code: 1,
                    user: omit(user, ['password', 'salt'])
                }
            } else {
                return {
                    code: 2,
                    user: null,
                    message: '密码错误'
                }
            }
        }
        return {
            code: 3,
            user: null,
            message: '没有此账号'
        };
    }

    // JWT验证 - Step 3: 处理 jwt 签证
    async certificate(user: any) {
        const payload = {
            username: user.username,
            sub: user.userId,
            realname: user.realName,
            role: user.role
        }
        console.log('JWT验证 - Step 3: 处理 jwt 签证');
        try {
            const token = this.jwtService.sign(payload)
            return {
                code: 200,
                data: {
                    token,
                    userInfo: user
                },
                msg: `登录成功`
            }
        } catch (error) {
            return {
                code: 600,
                msg: `账号或密码错误`,
            };
        }
    }
}
